#include "evdeploy/utils/report/tool_report.h"
#include "evdeploy/utils/report/cJSON.h"
#include <glog/logging.h>
#include <stdlib.h>

namespace ev
{

    ToolReport::ToolReport(){};

    ToolReport::~ToolReport(){};

    int ToolReport::report(const string &url, int algo_tool_type, const string &algo_tool_name,
                           const string &algo_tool_version, const string &remark)
    {
        std::map<std::string, std::string> head_list;
        head_list["Content-Type"] = "application/json;charset=UTF-8";
        cJSON *data = cJSON_CreateObject();
        cJSON_AddItemToObject(data, "algo_tool_type", cJSON_CreateNumber(algo_tool_type));
        cJSON_AddItemToObject(data, "algo_tool_name", cJSON_CreateString(algo_tool_name.c_str()));
        cJSON_AddItemToObject(data, "algo_tool_version", cJSON_CreateString(algo_tool_version.c_str()));
        cJSON_AddItemToObject(data, "remark", cJSON_CreateString(remark.c_str()));
        char *json_data = cJSON_Print(data);
        LOG(INFO) << "send report:"
                  << "\n"
                  << json_data;
        std::string response;
        int code = m_post.http_post(url, head_list, json_data, response);
        LOG(INFO) << "tool report response:" << response;
        cJSON_Delete(data);
        if (json_data)
            free(json_data);
        if (code == 0)
        {
            cJSON *res = cJSON_Parse(response.c_str());
            cJSON *res_data = cJSON_GetObjectItem(res, "code");
            char *data_value = cJSON_Print(res_data);

            if (strcmp(data_value, "20000") == 0)
            {
                LOG(INFO) << "tool report success";
                if (data_value)
                    free(data_value);
                cJSON_Delete(res);
                return 0;
            }
            else
            {
                LOG(INFO) << "tool report failed";
                if (data_value)
                    free(data_value);
                cJSON_Delete(res);
                return -1;
            }
        }
        return -1;
    }

    int ToolReport::report(int algo_tool_type, const string &algo_tool_name, const string &algo_tool_version,
                           const string &remark)
    {
        char *env_url = getenv("ALGO_TOOL_USAGE_REPORT_URL");
        if (env_url)
        {
            return report(env_url, algo_tool_type, algo_tool_name, algo_tool_version, remark);
        }
        else
        {
            LOG(INFO) << "ALGO_TOOL_USAGE_REPORT_URL not exists!!!";
            return -1;
        }
    }
} // namespace ev